package com.example.reactor.reactor;

import java.util.function.Consumer;
import java.util.function.Function;

public class Mono<T> implements Publisher<T> {
    private final T value;

    public Mono(T value) {
        this.value = value;
    }

    // map 操作符
    public <R> Mono<R> map(Function<? super T, ? extends R> mapper) {
        return new Mono<>(mapper.apply(value));
    }

    // flatMap 操作符
    public <R> Mono<R> flatMap(Function<? super T, Mono<R>> mapper) {
        return mapper.apply(value);
    }

    // doOnNext 操作符
    public Mono<T> doOnNext(Consumer<? super T> consumer) {
        consumer.accept(value);
        return this;
    }

    // doOnComplete 操作符
    public Mono<T> doOnComplete(Runnable runnable) {
        runnable.run();
        return this;
    }

    // doOnError 操作符
    public Mono<T> doOnError(Consumer<Throwable> consumer) {
        // No error in Mono by default, so we just call the consumer with a null Throwable.
        consumer.accept(null);
        return this;
    }

    @Override
    public void subscribe(Subscriber<? super T> subscriber) {
        subscriber.onNext(value);
        subscriber.onComplete();
    }
}